<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/27 17:19}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\controller;
use app\common\model\Detail;
use think\Db;
use app\api\model\Order;

class Notify
{
    // 回调信息
    public function order_wx_notify_url()
    {

        // 获取xml
        $xml        =   file_get_contents('php://input', 'r');
        // 转成php数组
        $arr        =   $this->xml2array($xml);
        //商户订单号
        $order_sn    =   $arr['out_trade_no'];  //订单单号
        //微信交易号
        $pay_sn      =   $arr['transaction_id'];  // 外部订单号
        // 订单金额
        $money       =   $arr['total_fee'];  // 订单的金额
        // 支付失败返回
        if ($arr['result_code'] != 'SUCCESS')
        {
            return false;
        }
        $order = Db::name('order_pay_money')->where('order_sn',$order_sn)->find();
        $UserModel = new \app\api\model\User();
        $userInfo = $UserModel->getUserInfo($order['uid']);
        $is_vip = $userInfo['is_vip'];
        $time = time();

        try {
            Db::startTrans();

                // 修改支付状态
                 Db::name('order_pay_money')
                    ->where('order_sn',$order_sn)
                    ->update(
                        [
                            'pay_sn' => $pay_sn,
                            'status' => 1,
                            'update_time' => $time
                        ]
                    );
                 // 获取价格百分比
                   $money = bcdiv($money, 100, 2);

                   $order_data = [
                        'order_status'   => 1,
                        'pay_status'     => 1,
                        'pay_way'        => 1,
                        'pay_time'       => $time,
                        'update_time'    => $time,
                        'refund_amount'  => $money,
                        'user_status'    => $is_vip,
                        'pay_out_sn'     => $pay_sn,
                        'pay_price'      => $money,
                    ];

                Order::where('pay_sn',$order_sn)->update($order_data);

                $list = Order::where('pay_sn',$order_sn)->select()->toArray();


                foreach($list as $key => $val){

                    Db::name('order')->where('id',$val['id'])->update(
                        ['pay_price' => $val['goods_pay_price'],
                        'refund_amount' =>  $val['goods_pay_price']]);
                }

                $order_li = Order::get(['pay_sn' => $order_sn]);

                $order_goods_list = Db::name('order_goods')
                    ->where('order_id',$order_li['id'])
                    ->select();

                if ($money > 1)
                {
                    //判断
                    $count = count($order_goods_list);
                    if ($count > 1)
                    {
                        $money = bcdiv($money, $count, 2);
                    }
                }

                $orderList = Order::where('pay_sn',$order_sn)
                    ->field('goods_num')
                    ->select()
                    ->toArray();
                $num = 0;
                foreach($orderList as $val)
                {
                    $num += $val['goods_num'];
                }

                $user_data = [
                    'price_sum'   => bcadd($userInfo['data']['price_sum'],$order['money']),
                    'number'      => bcadd($userInfo['data']['number'],1),
                    'unit_number' => bcadd($userInfo['data']['unit_number'],$num),
                ];
                Db::name('user')->where('id',$order['uid'])->update($user_data);
                Detail::addPrice($order['uid'],1,$money,$time);

            $res = true;
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            echo '支付错误';
            $res = false;
        }

        if ($res == false)
        {
            echo "fail";
        }else{
            echo "success";
        }

    }

    public function gold_wx_notify_url()
    {

        $xml        =   file_get_contents('php://input', 'r');
        $arr        =   $this->xml2array($xml);
        if ($arr['result_code'] != 'SUCCESS')
        {
            echo '支付失败1';
            return false;
        }

        $order_pay_money = Db::name('order_pay_money')
            ->where('order_sn',$arr['out_trade_no'])
            ->find();

        if (!$order_pay_money)
        {
            echo '支付失败2';
            return false;
        }

        if ($order_pay_money['status'] == 1)
        {
            echo '支付失败3';
            return false;
        }

        $pay_sn       = $arr['transaction_id'];
        $out_trade_no = $arr['out_trade_no']; // 单号
        $total_fee = $arr['total_fee']; // 金额
        $total_fee = bcdiv($total_fee, 100, 2);
        $time = time();

        try {
            Db::startTrans();
            $up_order_pay_sn = [
                'pay_sn' => $pay_sn,
                'status' => 1,
                'update_time' => $time
            ];
            $order_pay_sn = Db::name('order_pay_money')
                ->where('order_sn',$arr['out_trade_no'])
                ->update($up_order_pay_sn);
            if (!$order_pay_sn)
            {
                echo '支付失败';
                return false;
            }

            $data = [
                'status'          => 1,
                'pay_order_sn'    => $pay_sn,
                'pay_create_time' => $time,
                'price'           => $total_fee,
            ];

            $orderup = Db::name('user_order')
                ->where('pay_sn',$out_trade_no)
                ->update($data);

            if (!$orderup)
            {
                echo '支付失败了';
                return false;
            }

            Db::name('user')
              ->where('id',$order_pay_money['uid'])
              ->setInc('money', $total_fee);

            Db::name('user')
                ->where('id',$order_pay_money['uid'])
                ->setField('is_price', 1);

            $user_money_data = [
                'money' => $total_fee,
                'uid'   => $order_pay_money['uid'],
                'type'  => 'topup',
                'create_time'  => $time,
                'is_type'=> 1,
            ];
            Db::name('user_money')->insert($user_money_data);
            Detail::addPrice($order_pay_money['uid'],1,$total_fee,$time);
            Db::commit();
            $result = true;
        }catch(\Exception $e){
            Db::rollback();
            echo '支付错误';
            $result = false;
        }

        if ($result == false)
        {
            echo "fail";
        }else{
            echo "success";
        }
    }


    /**
     * xml转数组
     */
    function xml2array($xml)
    {
        if (!$xml) return array();
        libxml_disable_entity_loader(true);
        $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array;
    }
}